
import React, { Component } from 'react'

import { PAGE_SIZE } from '../../utils/constant.js'
import { formateDate } from '../../utils/dateUtils.js'

import { reqGetAllUsers, reqAddOrUpdateUser, reqDeleteUser } from '../../api/admin'

import AddOrUpdateUser from './AddOrUpdateUser'

import {
  Card,
  Button,
  Table,
  Modal,
  message
} from 'antd'


export default class User extends Component {

  state = {
    users: [],
    roles: [],
    isShow: false
  }

  initColumns = () => {
    this.columns = [
      {
        title: '用户名',
        dataIndex: 'username',
      },
      {
        title: '邮箱',
        dataIndex: 'email',
      },
      {
        title: '电话',
        dataIndex: 'phone',
      },
      {
        title: '注册时间',
        dataIndex: 'create_time',
        render: formateDate
      },
      {
        title: '所属角色',
        dataIndex: 'role_id',
        render: (role_id) => this.roleNames[role_id]
      },
      {
        title: '操作',
        render: (user) => (
          <span>
            <Button type="link" onClick={() => this.openUpdateUser(user)}>修改</Button>
            <Button type="link" onClick={() => this.deleteUser(user)}>删除</Button>
          </span>
        )
      },
    ]
  }

  getUsersList = async () => {
    const result = await reqGetAllUsers()
    if (result.status === 0) {
      this.initRoleNames(result.data.roles)
      this.setState({
        users: result.data.users,
        roles: result.data.roles
      })
    } else {
      message.error('请求出错了，请检查网络')
    }
  }

  /*
  根据role的数组, 生成包含所有角色名的对象(属性名用角色id值)
   */
  initRoleNames = (roles) => {
    const roleNames = roles.reduce((pre, role) => {
      pre[role._id] = role.name
      return pre
    }, {})
    // 保存
    this.roleNames = roleNames
  }

  //打开添加用户的modal
  openAddUser = () => {
    this.user = null
    this.setState({
      isShow: true
    })
  }

  //打开修改用户的modal
  openUpdateUser = (user) => {
    console.log(user);
    this.user = user // 保存user
    this.setState({
      isShow: true
    })
  }

  //添加用户
  addOrUpdateUser = async () => {
    this.form.validateFields()
      .then(async (values) => {
        const user = values
        // 如果是更新, 需要给user指定_id属性
        if (this.user) {
          user._id = this.user._id
        }
        const result = await reqAddOrUpdateUser(values)
        if (result.status === 0) {
          message.success(`${this.user ? '修改' : '添加'}用户成功!`)
          this.setState({
            isShow: false
          })
          this.getUsersList()
        } else {
          message.error(`${this.user ? '修改' : '添加'}用户失败!`)
        }
      })
      .catch(error => {
        message.error('出错了！')
      })

  }

  //关闭modal
  handleClose = () => {
    this.setState({
      isShow: false
    })
  }

  //传给子组件的方法，目的是获取子组件的值,子组件将值以参数的形式传给父组件
  setForm = (form) => {
    this.form = form
    console.log(this.form);
  }

  //删除用户
  deleteUser = async (user) => {
    Modal.confirm({
      title: `确认删除${user.username}吗?`,
      onOk: async () => {
        const result = await reqDeleteUser({ userId: user._id })
        if (result.status === 0) {
          message.success('删除用户成功!')
          this.getUsersList()
        }
      }
    })
  }

  UNSAFE_componentWillMount () {
    this.initColumns()
  }

  componentDidMount () {
    this.getUsersList()
  }

  render () {
    const { users, isShow } = this.state
    const user = this.user || {}
    const title = (
      <Button type="primary" onClick={this.openAddUser}>创建用户</Button>
    )

    return (
      <Card title={title}>
        <Table
          dataSource={users}
          columns={this.columns}
          rowKey='_id'
          bordered
          pagination={{
            defaultPageSize: PAGE_SIZE,
            showQuickJumper: true,
            showTitle: 'true'
          }}
        />
        <Modal
          title={user._id ? '修改用户' : '添加用户'}
          destroyOnClose
          visible={isShow}
          onOk={this.addOrUpdateUser}
          onCancel={this.handleClose}
        >
          <AddOrUpdateUser setForm={this.setForm} user={user} />
        </Modal>
      </Card>
    )
  }
}
